package com.seek.service.imp;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.bankfourfactor.BankCarFactorEntity;
import com.bankfourfactor.BankCarFactoryConstant;
import com.bankfourfactor.ResParam;
import com.bankfourfactor.youdun.PartnerRequest;
import com.seek.cache.CacheUtil;
import com.seek.common.handler.SpringContextHolder;
import com.seek.service.BankFourFactorService;
import com.seek.service.BizFlowService;
import com.seek.service.CustomerCardService;
import com.seek.service.CustomerService;
import com.seek.util.CommonUtil;

import net.sf.json.JSONObject;
@Repository("udBankFourFactorService")
public class UDBankFourFactorServiceImpl implements BankFourFactorService{
	 private static  CustomerCardService  customerCardService =  (CustomerCardService)SpringContextHolder.getBean("customerCardService");
	 private static BizFlowService bizFlowService = (BizFlowService)SpringContextHolder.getBean("bizFlowService"); 
	 private static CustomerService customerService = (CustomerService)SpringContextHolder.getBean("customerService"); 
	 private static Logger logger = LoggerFactory.getLogger(UDBankFourFactorServiceImpl.class); 
	
		@Override
		@Transactional(propagation = Propagation.REQUIRES_NEW)
		public Map<String, Object> process(Map<String,String> publicParams,BankCarFactorEntity b) {
		    //0:调用失败，1：调用成功，2：调用成功，内部方法出错
			int  processCode = 0;
			String orderNo = "";
			String bizFlowStatus = "0";
			String resJson = "";
			String respCode = "";
			JSONObject json = null;
			Map<String,Object> resultMap = new HashMap<String,Object>();
			try {
				logger.error("==========================BankCarFactorEntity========"+JSON.toJSONString(b));
				 resJson = PartnerRequest.apiCall(BankCarFactoryConstant.YOUDUN_URL,BankCarFactoryConstant.PUBLIC_KEY_ONLINE, BankCarFactoryConstant.BUSINESS_PRIVATE_KEY,BankCarFactoryConstant.YOUDUN_PRODUCT_CODE,b.getSeq(),publicParams);
				 json = JSONObject.fromObject(resJson);
				 logger.info(json.toString()+"有盾返回的数据");
				 respCode= json.getJSONObject("header").getString("ret_code");
				 logger.info("UDheader{ret_code:"+respCode+"}");
				
			} catch (Exception e) {
				
				e.printStackTrace();
			}
			try {
				if("000000".equals(respCode)){
					 bizFlowStatus = "1";
					//有盾接口对接成功
					 JSONObject body = json.getJSONObject("body");
					 logger.info(body.toString()+"有盾调用成功，返回的验证信息");
					 String status = body.getString("status");//有盾返回验证信息
					 String message = body.getString("message");//认证信息
					  orderNo = body.getString("ud_order_no");//有盾返回的交易号，楠云是没有的
					 String orgName = body.getString("org_name");//返回的银行卡名称
					 publicParams.put("status", status);
					 ResParam param = new ResParam();
					 int cardStatus = CommonUtil.getIntValue(publicParams.get("status"))==1?2:3;
					 param.setCode(cardStatus+"");
					 param.setMessage(message);
					 param.setBankName(orgName);
					 String cardNumber = b.getCardNo();
					 param.setCardNo("**** **** **** "+StringUtils.substring(cardNumber,cardNumber.length()-4));
					 resultMap.put("param", param);
					 //修改银行卡绑定信息
					 String updateCardSql = "update t_customer_card set audit_status=? , audit_remark=? , audit_time=now(),bank_name=? where  customer_id=? and history=0";
					 customerCardService.executeUpdate(updateCardSql,new Object[]{CommonUtil.getIntValue(status),message,orgName,b.getCustId()});
					 String updateCustomerSql = "update t_customer set card_bind_status=? where id = ?";
					 customerService.executeUpdate(updateCustomerSql,new Object[]{cardStatus,CommonUtil.getLongValue(b.getCustId())});
					 String custToken = CacheUtil.getRedisData("COUSTOMER_TOKEN_" + b.getCustId());  
					 //不知道失败是否刷新缓存
					 Map<String,Object> m = new HashMap<String,Object>();
					 if(CommonUtil.getIntValue(status)==1){
						 m.put("bankName", orgName);
						 m.put("cardNumber", b.getCardNo());
					 }else{
						 m.put("bankName", null);
						 m.put("cardNumber",null);
					 }
					 m.put("cardBindStatus",cardStatus);
					 CacheUtil.refreshCustRedis(custToken, m);
					 processCode = 1;
				 }
			} catch (Exception e) {
				processCode = 2;
			}
			 String bizFlowSql = "update t_biz_flow set modify_time=?,status=?,org_biz_no=?,org_code =? where biz_no = ? and deleted=0";
			 try {
				bizFlowService.updateBizFlow(bizFlowSql, new Object[]{new Date(),bizFlowStatus,orderNo,"YOUDUN",b.getSeq()});
			} catch (Exception e) {
				e.printStackTrace();
			}
			logger.info(processCode+"===========processCode=================");
			 resultMap.put("processCode", processCode);
			 return resultMap;
		}
}
